package shoppingmall.common.transitionalInformation;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import shoppingmall.common.dto.Result;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.Timer;


/**
 * 发送信息、接收信息
 */
@RestController
public class Message {

    //hashMap临时存储消息
    public static HashMap<String,String> hashMap = new HashMap<>();

    //发送消息
    @GetMapping("/api/sendMessage")
    public Result sendMessage (@RequestParam String message) {
        //往hashMap中存储消息
        //获取时间戳作为key
        long timeKey = new Date().getTime();
        hashMap.put(String.valueOf(timeKey),message);
        //返回获取消息的地址
        String acceptMsgAddress = getServerAddress() + "/api/acceptMessage?word=" + timeKey;
        HashMap<String,String> temp = new HashMap<>();
        temp.put("消息发送成功,获取消息请访问:",acceptMsgAddress);
        return Result.success(temp);
    }

    //接收数据
    @GetMapping("/api/acceptMessage")
    public Result acceptMessage (@RequestParam String word) {
        if(word == null || word == ""){
            return Result.error("query参数错误!");
        }
        String msg = hashMap.get(word);
        if(msg == null){
            return Result.error("呕吼,消息被清除了!");
        }
        //返回消息
        HashMap<String, String> temp = new HashMap<>();
        temp.put("会话消息:",msg);
        return Result.success(temp);
    }


    //启动定时任务
    public static void startTimedTask () {
        Timer timer = new Timer();
        MyTimerTask task = new MyTimerTask();
        long delay = 1000; // 延迟1秒执行
        long period = 1000*60*30; // 每隔30分钟执行一次
        timer.schedule(task, delay, period);
    }

    //清除hashMap的临时数据
    public static void clearHashmap () {
        hashMap.clear();
    }

    //读取properties配置文件信息(服务器地址信息)
    public static String getServerAddress () {
        Properties properties = new Properties();
        InputStream inputStream = null;
        String serverAddress = null;
        try {

            //开发环境下采用这种方式读取
            inputStream = ClassLoader.getSystemResourceAsStream("application.properties");
            //打成jar包上线采用这种方式读取
            //inputStream = new FileInputStream("application.properties");
            properties.load(inputStream);

            serverAddress = properties.getProperty("server_address");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return serverAddress;
    }
}
